package com.sikaryofficial.backend.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.sikaryofficial.backend.annotation.Repeat;
import com.sikaryofficial.backend.annotation.TenantFilter;
import com.sikaryofficial.backend.config.TenantFilterProperties;
import com.sikaryofficial.backend.constant.ProductStyleEnum;
import com.sikaryofficial.backend.domain.dto.SysDictDataDTO;
import com.sikaryofficial.backend.domain.dto.req.BrandTasteNameReq;
import com.sikaryofficial.backend.domain.dto.req.BrandTasteReq;
import com.sikaryofficial.backend.domain.dto.req.BrandTasteWithSpecialReq;
import com.sikaryofficial.backend.domain.vo.ModelVO;
import com.sikaryofficial.backend.manager.ProductManager;
import com.sikaryofficial.backend.service.IAttachmentService;
import com.sikaryofficial.backend.service.IBrandTasteService;
import com.sikaryofficial.backend.service.brand.cache.BrandTasteCacheService;
import com.sikaryofficial.backend.utils.ProductUtil;
import com.sikaryofficial.common.core.constant.BrandEnum;
import com.sikaryofficial.common.core.constant.HttpStatus;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.core.utils.HiResultUtil;
import com.sikaryofficial.common.core.utils.PageUtil;
import com.sikaryofficial.common.core.web.controller.BaseController;
import com.sikaryofficial.common.core.web.domain.HiResult;
import com.sikaryofficial.common.core.web.domain.PageResult;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.RemoteQrCodeService;
import com.sikaryofficial.system.api.model.product.BrandTasteDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 品牌口味Controller
 *
 * @author qinjinyuan
 * @date 2023-11-07
 */
@RestController
@RequestMapping("/brandTaste")
@Api(tags = "产品管理")
@Slf4j
public class BrandTasteController extends BaseController {

    @Autowired
    private ProductManager productManager;

    @Autowired
    private IBrandTasteService brandTasteService;
    @Autowired
    private BrandTasteCacheService brandCacheService;
    @Autowired
    private IAttachmentService attachmentService;
    @Autowired
    private RemoteQrCodeService remoteQrCodeService;
    @Resource
    private TenantFilterProperties tenantFilterProperties;

    /**
     * 通过HexId获取产品
     * <p>
     * param = 扫码url参数（HexStr(产品ID)+ seqno + 4位随机编码）
     */
    @Deprecated
    @GetMapping("/{param}")
    @ApiOperation("通过HexId获取产品")
    public HiResult<BrandTasteDTO> queryQrCodeByParam(@PathVariable("param") String param) {
        String[] params = param.split(ProductUtil.PARAM_SPLIT_KEY);
        BrandTasteDTO brandTasteDTO;
        if (params.length == 1) {
            brandTasteDTO = brandCacheService.getSignBrandTaste(ProductUtil.getIdByHexStr(params[0]));
        } else {
            // 逻辑：增加二维码param是否存在
            R<Boolean> existProductQrCode = remoteQrCodeService.existProductQrCode(param);
            if (Objects.isNull(existProductQrCode) || Boolean.FALSE.equals(existProductQrCode.getData())) {
                throw new ServiceException("the qrcode is not found:" + param, HttpStatus.ERROR);
            }
            brandTasteDTO = brandCacheService.brandByHexId(params[0]);
        }
        if (Objects.isNull(brandTasteDTO)) {
            throw new ServiceException("the product is not found:" + param, HttpStatus.ERROR);
        }
        return HiResultUtil.success(brandTasteDTO);
    }

    /**
     * 查询款式列表
     */
    @PostMapping("/styleList")
    @ApiOperation("款式列表")
    public HiResult<List<SysDictDataDTO>> styleList() {
        ProductStyleEnum[] feedbackTypeEnums = ProductStyleEnum.values();
        List<SysDictDataDTO> result = new ArrayList<>();
        for (ProductStyleEnum feedbackTypeEnum : feedbackTypeEnums) {
            SysDictDataDTO sysDictDataDTO = new SysDictDataDTO();
            result.add(sysDictDataDTO);
            sysDictDataDTO.setDictLabel(feedbackTypeEnum.getCode());
            sysDictDataDTO.setDictDesc(feedbackTypeEnum.getDesc());
            sysDictDataDTO.setDictValue(feedbackTypeEnum.getCode());
            sysDictDataDTO.setDictType("product_style");
        }
        return HiResultUtil.success(result);
    }

    /**
     * 查询品牌口味列表
     */
    @PostMapping("/brandList")
    @ApiOperation("口味评价-品牌列表")
    public HiResult<List<String>> brandList() {
        Set<String> list = brandCacheService.brandList();
        String inputBrand = SecurityUtils.getBrand();
        if (CollUtil.isNotEmpty(list) && BrandEnum.HISMK.getCode().equalsIgnoreCase(inputBrand)) {
            return HiResultUtil.success(list.stream().sorted(String::compareTo).collect(Collectors.toList()));
        }
        if (CollUtil.isNotEmpty(list) && CharSequenceUtil.isNotBlank(inputBrand)) {
            list = list.stream().filter(item -> item.equalsIgnoreCase(inputBrand)).collect(Collectors.toSet());
        }
        return HiResultUtil.success(list);
    }

    /**
     * 查询品牌口味列表
     */
    @PostMapping("/list")
    @ApiOperation("查询品牌口味(产品)列表")
    public PageResult<BrandTasteDTO> list(@Validated @RequestBody BrandTasteReq req) {
        IPage<BrandTasteDTO> page = brandTasteService.getBrandTasteList(req);
        return PageUtil.success(page.getRecords(), page.getTotal());
    }

    /**
     * V3.5 品牌专栏-产品系列列表
     */
    @PostMapping("/seriesList")
    @ApiOperation("V3.5 品牌专栏-产品系列")
    @TenantFilter
    @Repeat
    public R<List<String>> seriesList(@Validated @RequestBody BrandTasteNameReq req) {
        Integer tenantId = tenantFilterProperties.getTenantByBrand(req.getBrandNo());
        if (Objects.isNull(tenantId)) {
            return R.ok(Lists.newArrayList());
        }
        List<BrandTasteDTO>  brandTasteDTOS =  brandCacheService.getBrandTasteListByTenantId(tenantFilterProperties.getTenantByBrand(req.getBrandNo()));
        Set<String> productNameSet =
                brandTasteDTOS.stream().map(BrandTasteDTO::getProductName).collect(Collectors.toSet());
        return R.ok(productNameSet.stream().sorted(String::compareTo).collect(Collectors.toList()));
    }

    /**
     * V2.5 品牌专栏-产品列表
     */
    @PostMapping("/listWithBrandSpecial")
    @ApiOperation("V2.5 品牌专栏-产品列表")
    @TenantFilter
    @Repeat
    public PageResult<BrandTasteDTO> listWithBrandSpecial(@Validated @RequestBody BrandTasteWithSpecialReq req) {
        IPage<BrandTasteDTO> page = productManager.listWithBrandSpecial(req);
        return PageUtil.success(page.getRecords(), page.getTotal());
    }

    /**
     * 查询model列表
     */
    @PostMapping("/modelList")
    @ApiOperation("口味评价-型号列表")
    public HiResult<List<ModelVO>> modelList(@Validated @RequestBody BrandTasteReq req) {
        return HiResultUtil.success(brandCacheService.modelList(req));
    }

    /**
     * 查询口味列表
     */
    @PostMapping("/tasteList")
    @ApiOperation("口味评价-口味列表")
    public HiResult<List<String>> tasteList(@Validated @RequestBody BrandTasteReq req) {
        return HiResultUtil.success(brandCacheService.tasteList(req));
    }

    /**
     * 查询口味列表
     */
    @PostMapping("/styleListByParam")
    @ApiOperation("口味评价-款式列表")
    public HiResult<List<BrandTasteDTO>> styleListByParam(@Validated @RequestBody BrandTasteReq req) {
        return HiResultUtil.success(brandCacheService.styleListByParam(req));
    }

    /**
     * 产品详情
     */
    @GetMapping("/detail/{brandTasteId}")
    @ApiOperation("产品详情")
    @Repeat
    public HiResult<BrandTasteDTO> detail(@PathVariable("brandTasteId") Long brandTasteId) {
        BrandTasteDTO brandTasteDTO = brandCacheService.getSignBrandTaste(brandTasteId);
        if (Objects.nonNull(brandTasteDTO)) {
            // 附件
            brandTasteDTO.setAttachmentList(attachmentService.getAttachmentById(brandTasteDTO.getBrandTasteId()));
        }
        return HiResultUtil.success(brandTasteDTO);
    }
}
